<template>
  <div>
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <!-- 周次 -->
        <!-- <el-select v-model="week" placeholder="请选择周次">
          <el-option
            v-for="item in weeks"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <el-select v-model="week" placeholder="请选择星期" @change="selectWeek" style="margin-bottom: 15px;">
          <el-option
            v-for="item in Selectweeks"
            :key="item"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="college"
          placeholder="请选择学院"
          @change="selectCollege"
          style="margin-bottom: 15px;"
        >
          <el-option
            v-for="item in collegeArr"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="specialized"
          placeholder="请选择专业"
          @change="Selectspecialized"
          style="margin-bottom: 15px;"
        >
          <el-option
            v-for="item in specializedArr"
            :key="item"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="VClasses"
          placeholder="请选择班级"
          @change="SelectClasses"
          style="margin-bottom: 15px;"
        >
          <el-option
            v-for="(item, index) in VClassesArr"
            :key="index"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-button type="info" @click="reset"  size="small">重置</el-button>
        <el-radio-group v-model="filterMode" @change="applyFilters" style="margin-left: 20px;">
          <el-radio label="single">单条筛选</el-radio>
          <el-radio label="combined">联动筛选</el-radio>
        </el-radio-group>
        <!-- 保留数据上传 -->
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-change="handleChangeKeepData"
          :before-remove="beforeRemove"
          :headers="{ Authorization: header }"
          :on-success="uploadSuccessKeepData"
          :multiple="false"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileListKeep"
          ref="uploadKeep"
          :auto-upload="false"
          style="float: right; margin-right: 10px;"
        >
          <el-button size="small" type="success">保留数据上传</el-button>
        </el-upload>
        
        <!-- 删除数据上传 -->
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-change="handleChangeDeleteData"
          :before-remove="beforeRemove"
          :headers="{ Authorization: header }"
          :on-success="uploadSuccessDeleteData"
          :multiple="false"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileListDelete"
          ref="uploadDelete"
          :auto-upload="false"
          style="float: right"
        >
          <el-button size="small" type="danger">删除数据上传</el-button>
        </el-upload>
      </el-col>
    </el-row>

    <el-table
      border
      :data="
        count == 0
          ? classTable.slice((current - 1) * size, current * size)
          : newclassTable.slice((current - 1) * size, current * size)
      "
      style="width: 100%; margin-top: 20px; text-align: center"
    >
      <el-table-column
        prop="weeks"
        label="上课周次"
        width="150"
        style="text-align: center"
      >
      </el-table-column>
      <el-table-column prop="week" label="星期" width="120"> </el-table-column>
      <el-table-column prop="college" label="学院" width="120"> </el-table-column>
      <el-table-column prop="classroom" label="教室名"> </el-table-column>
      <!-- <el-table-column prop="course" label="专业名"> </el-table-column> -->
      <el-table-column prop="course" label="课程名称"> </el-table-column>
      <el-table-column prop="classes" label="上课班级"> </el-table-column>
      <el-table-column prop="shouldArrival" label="上课人数" width="120">
      </el-table-column>
      <el-table-column prop="counsellor" label="辅导员" width="130">
      </el-table-column>
      <el-table-column prop="teacher" label="任课教师" width="150">
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20,50,100]"
      :current-page.sync="current"
      :page-size="size"
      layout="sizes, prev, pager, slot"
      :total="count == 0 ? classTable.length : newclassTable.length"
      row-key
    >
      <el-button
        type="text"
        @click="showMore"
        v-show="
          count == 0
            ? classTable.length / size > 1
            : newclassTable.length / size > 1
        "
        >下一页</el-button
      >
    </el-pagination>
  </div>
</template>

<script>
import Cookies from "js-cookie";
export default {
  data() {
    return {
      // 请选择星期
      week: "",
      Selectweeks: [
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
        "星期日",
      ],
      //   请选择班级
      selectsClass: [],
      selectClass: "",
      tableData: [],
      fileList: [],
      fileListKeep: [], // 保留数据上传的文件列表
      fileListDelete: [], // 删除数据上传的文件列表
      uploadUrl: '/api/course/upload', // 上传URL
      header: Cookies.get("token"),
      classTable: [],
      size: 10,
      current: 1,
      options: [],
      Vcourse: "",
      VcourseArr: [],
      VClasses: "",
      VClassesArr: [],
      count: 0,
      newclassTable: [],
      specializedArr: [],
      specialized: "",
      college: "",
      collegeArr: [],
      originalData: [], // 保存原始数据
      filterMode: 'combined', // 'single' 单条筛选, 'combined' 联动筛选
    };
  },
  created() {
    this.courseList();
    setTimeout(() => {
      this.queryClasses();
    }, 500);
  },
  methods: {
    courseList() {
      this.$post("/api/course/list", {}).then((res) => {
        // console.log(res.data);
        this.classTable = res.data;
        this.originalData = [...res.data]; // 保存原始数据
        this.newclassTable = [...res.data]; // 初始化筛选结果
      });
    },
    // 保留数据上传成功回调
    uploadSuccessKeepData(response, file, fileList) {
      this.$message.success("保留数据上传成功！");
      this.courseList(); // 重新加载数据
      this.$refs.uploadKeep.clearFiles(); // 清空文件列表
    },
    
    // 删除数据上传成功回调
    uploadSuccessDeleteData(response, file, fileList) {
      this.$message.success("删除数据上传成功！");
      this.courseList(); // 重新加载数据
      this.$refs.uploadDelete.clearFiles(); // 清空文件列表
    },
    
    // 保留数据文件选择处理
    handleChangeKeepData(file, fileList) {
      let reg = /.*(xls|xlsx)$/;
      if (!reg.test(file.name)) {
        this.$message.error("请上传xls或xlsx格式的文件");
        return false;
      }
      this.fileListKeep = [file];
      // 立即执行上传
      this.performUpload(file, 0); // isDelete = 0 表示不删除数据
    },
    
    // 删除数据文件选择处理
    handleChangeDeleteData(file, fileList) {
      let reg = /.*(xls|xlsx)$/;
      if (!reg.test(file.name)) {
        this.$message.error("请上传xls或xlsx格式的文件");
        return false;
      }
      this.fileListDelete = [file];
      // 立即执行上传
      this.performUpload(file, 1); // isDelete = 1 表示删除数据
    },
    
    // 执行上传的统一方法
    performUpload(file, isDelete) {
      const formData = new FormData();
      formData.append('file', file.raw);
      formData.append('isDelete', isDelete);
      
      this.$post('/api/course/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': this.header
        }
      }).then(res => {
        if (res.code === 200) {
          if (isDelete === 0) {
            this.uploadSuccessKeepData(res, file, []);
          } else {
            this.uploadSuccessDeleteData(res, file, []);
          }
        } else {
          this.$message.error(res.message || '上传失败');
        }
      }).catch(error => {
        console.error('Upload error:', error);
        this.$message.error('上传失败，请稍后重试');
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 分页
    handleSizeChange(val) {
      this.size = val;
    },
    handleCurrentChange(val) {
      this.current = val;
    },
    showMore() {
      if (this.count == 1) {
        if (this.current < this.newclassTable.length / this.size) {
          this.current++;
          // console.log( this.current);
        } else {
          this.$message({
            message: "已经是最后一页",
            type: "warning",
          });
        }
      } else {
        if (this.current < this.classTable.length / this.size) {
          this.current++;
          // console.log( this.current);
        } else {
          this.$message({
            message: "已经是最后一页",
            type: "warning",
          });
        }
      }
    },
    //星期
    selectWeek(val) {
      this.Vcourse = "";
      this.applyFilters();
    },
    Selectcourse(val) {
      this.count = 0;
      this.VClasses = "";
      this.VClassesArr = [];
    },
    SelectClasses() {
      this.applyFilters();
    },
    QueryAll() {
      this.applyFilters();
    },
    // 选择学院
    selectCollege() {
      this.applyFilters();
    },
    Selectspecialized() {
      this.VClasses = "";
      // 更新班级选项列表
      var d = [];
      this.originalData.forEach((item) => {
        if (item.classes && item.classes.indexOf(this.specialized) != -1) {
          d.push(item.classes);
        }
      });
      this.VClassesArr = Array.from(new Set(d));
      // 应用筛选
      this.applyFilters();
    },
    queryClasses() {
      var a = [];
      var b = [];
      var d = [];
      var colleges = []; // 学院数组
      this.originalData.forEach((item) => {
        a.push(item.course);
        b.push(item.classes);
        colleges.push(item.college); // 提取学院数据
        this.VcourseArr = Array.from(new Set(a));
        if (item.classes && item.classes.indexOf(this.specialized) !== -1) {
          d.push(item.classes);
        }
      });
      var c = [];
      for (var i = 0; i < b.length; i++) {
        if (b[i]) {
          c.push(b[i].split(/(\d+)|\[|\]/)[0]);
        }
      }
      this.specializedArr = Array.from(new Set(c.filter(item => item)));
      this.collegeArr = Array.from(new Set(colleges.filter(college => college))); // 去重并过滤空值
    },
    // 统一筛选方法
    applyFilters() {
      this.count = 1;
      let filteredData = [...this.originalData];
      
      if (this.filterMode === 'combined') {
        // 联动筛选：多个条件同时生效
        if (this.week) {
          filteredData = filteredData.filter(item => item.week === this.week);
        }
        if (this.college) {
          filteredData = filteredData.filter(item => item.college === this.college);
        }
        if (this.specialized) {
          filteredData = filteredData.filter(item => 
            item.classes && item.classes.indexOf(this.specialized) !== -1
          );
        }
        if (this.VClasses) {
          filteredData = filteredData.filter(item => item.classes === this.VClasses);
        }
      } else {
        // 单条筛选：只按最后一个有值的条件筛选
        if (this.VClasses) {
          filteredData = filteredData.filter(item => item.classes === this.VClasses);
        } else if (this.specialized) {
          filteredData = filteredData.filter(item => 
            item.classes && item.classes.indexOf(this.specialized) !== -1
          );
        } else if (this.college) {
          filteredData = filteredData.filter(item => item.college === this.college);
        } else if (this.week) {
          filteredData = filteredData.filter(item => item.week === this.week);
        }
      }
      
      this.newclassTable = filteredData;
      this.current = 1; // 重置到第一页
    },
    
    // 重置
    reset(){
      this.count = 0;
      this.week = '';
      this.college = '';
      this.specialized = '';
      this.VClasses = '';
      this.VClassesArr = [];
      this.newclassTable = [...this.originalData];
      this.current = 1;
    }
  },
};
</script>

<style scoped>
.el-table >>> .cell {
  text-align: center;
}

.upload-demo >>> .el-upload-list {
  display: none;
}
</style>